package server;

import org.apache.commons.lang3.text.StrSubstitutor;

import javax.servlet.Servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class ServletProcessor {
    private static String OKMessage = "HTTP/1.1 ${StatusCode} ${StatusName}\r\n" +
            "Content-Type: ${ContentType}\r\n" +
            "Server: minit\r\n" +
            "Date: ${ZonedDateTime}\r\n" +
            "\r\n";

    public void process(HttpRequest request, HttpResponse response) {
        // 首先根据uri最后一个/号来定位，后面的字符串认为是servlet名字
        String uri = request.getRequestURI();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        URL url = null;
        try {
            File classPath = new File(HttpSever.WEB_ROOT);
            url = new URL("file", null, classPath.getCanonicalPath() + File.separator);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        URLStreamHandler streamHandler = null;
        // File classPath = new File(HttpSever.WEB_ROOT);
        // String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
        // urls[0] = new URL(null, repository, streamHandler);
        // loader = new URLClassLoader(urls);
        response.setCharacterEncoding("UTF-8");
        // PrintWriter writer = null;
        // try {
        //     writer = response.getR();
        // } catch (IOException e) {
        //     throw new RuntimeException(e);
        // }

        // create a URLClassLoader
        try (URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{new URL(null, url.toString(), streamHandler)})) {
            // 由上面的URLClassLoader加载这个servlet
            Class<?> aClass = urlClassLoader.loadClass(servletName);
            Servlet servlet = (Servlet) aClass.newInstance();

            response.sendHeaders();
            servlet.service(new HttpRequestFacade(request), new HttpResponseFacade(response));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 写响应头

        // 创建servlet新实例，然后调用service()，由它来写动态内容到响应体
    }

    // private String composeResponseHead() {
    //     Map<String, String> valuesMap = new HashMap<>();
    //     valuesMap.put("StatusCode", "200");
    //     valuesMap.put("StatusName", "OK");
    //     valuesMap.put("ContentType", "text/html;charset=uft-8");
    //     valuesMap.put("ZonedDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ZonedDateTime.now()));
    //     StrSubstitutor sub = new StrSubstitutor(valuesMap);
    //     String responseHead = sub.replace(OKMessage);
    //     return responseHead;
    // }
}
